/**
 * Copyright (C), 2015-2019, XXX有限公司
 * FileName: CustSyncData
 * Author:   Administrator
 * Date:     2019/8/29 9:58
 * Description: 同步数据
 * History:
 * <author>          <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号              描述
 */
package com.sunlord.controller;

import OThinker.Common.Organization.Models.User;
import OThinker.H3.Portal.webservices.Entity.BPMServiceResult;
import OThinker.H3.Portal.webservices.impl.BPMServiceImpl;
import com.alibaba.fastjson.JSONObject;
import com.sunlord.utils.DbConfigUtil;
import com.sunlord.utils.NewDbConfigUtil;
import com.sunlord.workflow.WorkflowNewParam;
import com.sunlord.workflow.WorkflowNewRet;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.sql.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 〈一句话功能简述〉<br> 
 * 〈同步数据〉
 *
 * @author Administrator
 * @create 2019/8/29
 * @since 1.0.0
 */
@RestController
@RequestMapping("/syncData")
public class CustSyncData {
    private static final Logger LOGGER = LoggerFactory.getLogger(CustSyncData.class);

    public   final static   Map<String, Integer> pagingMap = new HashMap<>();


    private void initPagingMap (){

        if (pagingMap.isEmpty()){
            String sql = "SELECT BPCNUM FROM (SELECT ROWNUM AS rowno, t.BPCNUM  FROM I_BPCMASTER t   WHERE  ( BPCNUM != ''  or BPCNUM is not null) and  ROWNUM <= %s) table_alias WHERE table_alias.rowno >%s";



            int count = getPagingDataCount(NewDbConfigUtil.DBCODE_SUNLORD_ENGINE_ORACLE, "I_BPCMASTER");



            System.out.println("总数"+count);

            int loop = 200;
            for (int i = 0; i < count; i+=loop) {

                List<Map<String, Object>> dataList = getData(NewDbConfigUtil.DBCODE_SUNLORD_ENGINE_ORACLE,
                        String.format(sql,  String.valueOf(i + loop), String.valueOf(i)));


                for (int j = 0; j < dataList.size(); j++) {
                    pagingMap.put(String.valueOf(dataList.get(j).get("BPCNUM")),1);
                }


            }




        }
        System.out.println(String.format("pagingMpa.size=%s", pagingMap.size()));

    }


    @RequestMapping("/removeSyncDataCache")
    public Object removeSyncDataCache(String bpcnum){
       return pagingMap.remove(bpcnum) ;
    }

    @RequestMapping("syncData")
    public  Object  syncData (){


        initPagingMap();

        //主表
        List<Map<String, Object>> list = null;

        JSONObject bpmJson = new JSONObject();

        int loopCount = 0;

        int count = getPagingDataCount(NewDbConfigUtil.DBCODE_SUNLORD_ENGINE_ORACLE, "I_BPCMASTER_ZJ");

        System.out.println("总数"+count);

        int loop = 200;
        for (int i = 0; i < count; i+=loop) {

            list = getPagingData(NewDbConfigUtil.DBCODE_SUNLORD_ENGINE_ORACLE,"I_BPCMASTER_ZJ",i,loop);

            System.out.println(list != null ? list.size():0);

            if (list == null || list.size() ==0){
                return false    ;
            }

            loopCount++;
            System.out.println("第"+loopCount+"获取 主表数据 ,list.size:"+list.size());

            startSyncFlowWorkData(list);

        }




        return  null;
    }


    /**
     *   开始启动流程
     * @param list
     */
    public void startSyncFlowWorkData (List<Map<String, Object>> list){


        if (list == null || list.size()==0){
            return;
        }

        String contactSql  = "SELECT * from I_CONTACTMASTER_ZJ WHERE BPCNUM = '%s'";
//        String contactSql  = "SELECT * from I_CONTACTMASTER WHERE PARENTOBJECTID = '%s'";

        String bpaddressSql = "SELECT * from I_BPADDRESSMASTER_ZJ WHERE BPCNUM = '%s'";
//        String bpaddressSql = "SELECT * from I_BPADDRESSMASTER WHERE PARENTOBJECTID = '%s'";



        for (int i = 0; i < list.size(); i++) {
            System.out.println("\n\n第"+i+"写入数据");
            Map<String, Object> map = list.get(i);

            String bpcnum = (String) map.get("BPCNUM");
//            String bpcnum = (String) map.get("OBJECTID");

            if (StringUtils.isNotBlank(bpcnum)){

                if (pagingMap.containsKey(bpcnum) && pagingMap.get(bpcnum) ==1){
                    System.out.println("已发起过流程bpcnum:"+bpcnum);
                    continue;
                }


                List<Map<String, Object>> contactList = getData(NewDbConfigUtil.DBCODE_SUNLORD_ENGINE_ORACLE, contactSql.format(contactSql, bpcnum));


                List<Map<String, Object>> bpaddressSqlList = getData(NewDbConfigUtil.DBCODE_SUNLORD_ENGINE_ORACLE, contactSql.format(bpaddressSql, bpcnum));


                if (contactList != null && contactList.size()>0 ){
                    map.put("CONTACTMASTER",contactList);
                    reomveTableDefaultKeyWord(contactList);
                }
                if (bpaddressSqlList != null && bpaddressSqlList.size()>0 ){
                    map.put("BPADDRESSMASTER",bpaddressSqlList);
                    reomveTableDefaultKeyWord(bpaddressSqlList);
                }

                reomveTableDefaultKeyWord(map);
                String paramValues = JSONObject.toJSONString(map);

                try {


                    WorkflowNewParam workflowParam = new WorkflowNewParam("BPCMASTER", User.AdministratorAlias, "true", paramValues.toString());

                    WorkflowNewRet ret = this.exworkflow(workflowParam);

                    if (ret.isSuccess()) {
                        System.out.println("流程发起成功，bpcnum:" + bpcnum);
                        pagingMap.put(bpcnum,1);

                    }
                } catch (Exception e) {
                    System.out.println("流程发起失败，bpcnum:" + bpcnum);

                    pagingMap.put(bpcnum,2);
                }





            }else {
                System.out.println("bpcnum is null:"+bpcnum);
            }



        }
    }



    public  final String [] MASTER_TABLE_DEFAULT_COLUS = {"OBJECTID","NAME","CREATEDBY","CREATEDBYPARENTID","OWNERID","OWNERPARENTID","CREATEDTIME","MODIFIEDBY","MODIFIEDTIME","RUNNINGINSTANCEID"};
    public  final String [] SON_TABLE_DEFAULT_COLUS = {"OBJECTID","PARENTOBJECTID","PARENTPROPERTYNAME"};


    /**
     *  过滤 系统默认字段
     * @param map
     */
    public void reomveTableDefaultKeyWord (Map<String,Object> map){
        if (map!= null){

            for (int i = 0; i < MASTER_TABLE_DEFAULT_COLUS.length; i++) {
                map.remove(MASTER_TABLE_DEFAULT_COLUS[i]);
            }

            for (int i = 0; i < SON_TABLE_DEFAULT_COLUS.length; i++) {
                map.remove(SON_TABLE_DEFAULT_COLUS[i]);
            }
        }
    }
    /**
     *  过滤 系统默认字段
     * @param list
     */
    public void reomveTableDefaultKeyWord(List<Map<String,Object>> list){
        if (list != null && list.size()>0){
            for (int i = 0; i < list.size(); i++) {
                reomveTableDefaultKeyWord(list.get(i));
            }
        }
    }



    public List<Map<String, Object>> getData(String dbCode,String sql){

         return NewDbConfigUtil.executeQuerySql(NewDbConfigUtil.CLASSNAME_ORACLE, dbCode, sql);

    }





    public int getPagingDataCount(String dbCode,String tableName ){

        String sql = "SELECT count(*) as COUNT from %s";

        List<Map<String, Object>> data = getData(dbCode, String.format(sql, tableName));

        if (data != null && data.size()>0 ){
            if (data.get(0)!= null && data.get(0).get("COUNT") != null  ){

                Integer count = Integer.valueOf(data.get(0).get("COUNT").toString());

                if (count != null){
                    return count;
                }
            }

        }

        return  0;
    }

    public List<Map<String, Object>> getPagingData(String dbCode,String tableName ,int index ,int size){

        String sql =  " SELECT * FROM (SELECT ROWNUM AS rowno, t.*  FROM %s t   WHERE  ROWNUM <= %s) table_alias WHERE table_alias.rowno > %s";
        List<Map<String, Object>> data = getData(dbCode, String.format(sql, tableName, String.valueOf(index + size), String.valueOf(index)));


        return data;
    }



    private static final BPMServiceImpl bpmService = new BPMServiceImpl();

    public WorkflowNewRet exworkflow(WorkflowNewParam param){
        try {

            BPMServiceResult result = bpmService.StartWorkflowNew("H3", "Authine", param.getWorkflowCode(), param.getUserCode(), param.getFinishStart(), param.getParamValues());
            return setRet(result);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 设置返回值
     * @param result BPMServiceResult
     * @return WorkflowNewRet
     */
    private WorkflowNewRet setRet(BPMServiceResult result) {
        WorkflowNewRet ret = new WorkflowNewRet();
        ret.setSuccess(result.isSuccess());
        ret.setMessage(result.getMessage());
        ret.setInstanceID(result.getInstanceId());
        ret.setWorkItemID(result.getWorkItemId());
        ret.setWorkItemUrl(result.getWorkItemUrl());
        return ret;
    }
}